<template>
  <div>
    聊天室(npm i ws
    <el-button @click="sendMsg">发送</el-button>
    <MdEditor style="margin-top: 10px" :content.sync="obj.content"></MdEditor>
  </div>
</template>

<script>
const ws = new WebSocket("ws://localhost:8000")
export default{
  data(){
    return{
      obj:{
        content:`
        const Ws = require('ws')
        const server = new Ws.Server({port:8000})
        const init = () => {
          bindEvent()
          server.clients.forEach(c=>{
              // console.log(c)
             c.send('hahahah')
         })
      }
      function bindEvent () {
          server.on('open',handlerOpen);
          server.on('close',handlerClose);
          server.on('error',handlerError);
          server.on('connection',handlerMessage);
      }
      function handlerOpen(){
          console.log("open")
      }
      function handlerClose(){
          console.log("close")
      }
      function handlerError(){
          console.log("error")
      }
      function handlerMessage(ws){
          console.log("message")
          ws.on("message",handlerMsg)
      }
      function handlerMsg(msg){
          // console.log(server.clients)
          server.clients.forEach(c=>{
              console.log(c)
              c.send(JSON.stringify({a:c}))
          })
      }
      init()
        `
      }
    }
  },
  mounted(){
    ws.addEventListener('open',this.wsOpen.bind(this),false)
    ws.addEventListener('close',this.wsClose.bind(this),false)
    ws.addEventListener('error',this.wsError.bind(this),false)
    ws.addEventListener('message',this.wsMessage.bind(this),false)

  },
  methods:{
    sendMsg(){
      ws.send(JSON.stringify(555555))
      console.log(this.obj)
    },
    wsOpen(e){
      console.log(e,'open')
    },
    wsClose(e){
      console.log(e,'close')
    },
    wsError(e){
      console.log(e,'error')
    },
    wsMessage(e){
      console.log(JSON.parse(e.data))
      console.log(e,'message')
    },
  }
}
</script>